import { defineStore } from 'pinia'
import { getUrlByFileNo } from '~/api/file'
import { addCollectArticle, deleteCollectArticle } from '~/api/home'

export const useGlobalStore = defineStore('global', () => {
  const isBigCharMode = ref(false)
  const setBigCharMode = (val: boolean) => {
    isBigCharMode.value = val
  }
  return {
    isBigCharMode,
    setBigCharMode,
  }
})

export function checkLogin(back?: boolean) {
  // const route = useRoute()
  const userStore = useUserStore()
  // userStore.setPathBeforeLogin(route.path)
  if (userStore.isLogin !== true) {
    ElNotification.warning({
      title: '提示',
      message: '请先登录',
    })
    userStore.setAllowCloseLogin(false)
    userStore.setLoginVisible(true)
    onUnmounted(() => {
      userStore.setAllowCloseLogin(true)
      userStore.setLoginVisible(false)
    })
    if (back === true) {
      const router = useRouter()
      router.go(-1)
    }
  }
}
export function copyText(text: string) {
  if (navigator.clipboard?.writeText) { // navigator.clipboard 是浏览器原生支持的剪贴板 API,只有在安全环境下才能使用，例如https协议、本地localhost等
    navigator.clipboard.writeText(text)
  }
  else {
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
  }
}
export function copyUrl() {
  const url = window.location.href
  copyText(url)
  ElMessage.success('已复制当前页面链接，可以去分享啦~')
}

export async function changeArticleCollect(id: string) {
  const { collectArticleMap } = useUserStore()
  const collectItem = collectArticleMap?.[id]
  console.log('collectItem', collectItem);
  
  if (collectItem?.id) {
    const res = await deleteCollectArticle([collectItem.id])
    if (res.state === 'SUCCESS') {
      ElMessage.success('取消收藏成功')
    }
  }
  else {
    const res = await addCollectArticle([id])
    if (res.state === 'SUCCESS') {
      ElMessage.success('收藏成功')
    }
  }
}
export function compressImage(url: string) {
  if (url?.includes('?')) {
    return `${url}&thumbnailType=fwsu_100`
  }
  else {
    return `${url}?thumbnailType=fwsu_100`
  }
  return `/api/compress-image?url=${encodeURIComponent(url)}`
}

export function getImgUrl(url: string, isCompress = false, placeholder?: string) {
  let imgUrl = ''
  if (!url) {
    imgUrl = placeholder || '/img/placeholder.jpg'
  }
  if (url?.indexOf('http') === 0) {
    imgUrl = url
  }
  else if (url) {
    imgUrl = getUrlByFileNo(url)
  }
  // if (isCompress) {
  //   imgUrl = compressImage(imgUrl)
  // }
  if (imgUrl?.includes('fileNo=') && !imgUrl?.includes('thumbnailType')) {
    imgUrl = `${imgUrl}&thumbnailType=fwsu_100`
  }
  if (imgUrl?.includes('myhuaweicloud.com')) {
    return `${url}?x-image-process=image/resize,w_500,limit_0/quality,q_80`
  }
  return imgUrl
}
